package com.nageoffer.jobtrain.projects.config;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 阿里云发送短信工具配置类
 * author：唐晨
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class AliYunSendMessageConfig {
    /**
     * 阿里云验证配置Bean
     */
    private final Client aliyunSmsClient;

    /**
     * 签名名称
     */
    @Value("${sms.aliyun.signName}")
    private String signName;

    /**
     * 模板code
     */
    @Value("${sms.aliyun.loginTemplateCode}")
    private String templateCode;

    /**
     * 发送验证码
     *
     * @param phoneNumber 手机号
     * @param sendCode    验证码
     * @return 是否发送成功
     */
    public boolean sendMessage(String phoneNumber, String sendCode) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("code", sendCode);
        String params = JSON.toJSONString(paramsMap);
        return sendMessageTemplate(phoneNumber, signName, templateCode, params);
    }

    /**
     * 发送验证码模板方法
     *
     * @param phoneNumber  手机号
     * @param signName     签名名称
     * @param templateCode 模板code
     * @param params       携带替换参数
     * @return 是否发送成功
     */
    public boolean sendMessageTemplate(String phoneNumber, String signName, String templateCode, String params) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumber)
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setTemplateParam(params);
        try {
            SendSmsResponse sendSmsResponse = aliyunSmsClient.sendSms(sendSmsRequest);
            SendSmsResponseBody sendSmsResponseBody = sendSmsResponse.getBody();
            if (!Objects.equals(sendSmsResponseBody.getCode(), "OK")) {
                log.error("短信验证码:{} 发送失败，失败原因:{}.... ", JSON.toJSONString(sendSmsRequest), sendSmsResponseBody.getMessage());
                return false;
            }
            log.info("短信验证码:{} 发送成功.... ", JSON.toJSONString(sendSmsRequest));
            return true;
        } catch (Throwable ex) {
            log.error("短信验证码:{} 发送异常，异常原因:{}.... ", JSON.toJSONString(sendSmsRequest), ex.getMessage());
            return false;
        }
    }
}
